//
//  WBOAuthViewController.swift
//  weiboswift
//
//  Created by dingzhibing on 2017/3/25.
//  Copyright © 2017年 dingzhibing. All rights reserved.
//

import UIKit
import SVProgressHUD
//通过webView加载新浪微博授权页面控制器
class WBOAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView   //将根视图换成webview
        view.backgroundColor = UIColor.white
        
        //设置代理
        webView.delegate = self
        
        webView.scrollView.isScrollEnabled = false
        
        title = "登录新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack:true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill), isBack: false)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURI)"
        
        guard let url = URL(string: urlString)else{
            return
        }
        
        let request = URLRequest(url: url)
        
        webView.loadRequest(request)
    }
    
    // MARK: - 监听方法
    @objc fileprivate func close(){
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    /// 自动填充 webview注入
    @objc private func autoFill(){
        //准备js
        let js = "document.getElementById('userId').value = '18910630564';" + "document.getElementById('passwd').value = 'dzb5461883'"
        //让webview执行js
        webView.stringByEvaluatingJavaScript(from: js)
    }
}

extension WBOAuthViewController:UIWebViewDelegate{
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print("加载的请求--- \(String(describing: request.url?.absoluteString))")
        //如果请求地址包含https://baidu.com不加载页面 ／否则加载
        if request.url?.absoluteString.hasPrefix(WBRedirectURI) == false{
            return true
        }
        
        if request.url?.query?.hasPrefix("code=") == false {
            print("取消授权")
            close()
            return false
        }
        
        //URL.scheme  -> 协议头
        //URL.host    -> 主机地址
        //URL.pathComponents   ->路径
        
        //代码走到这里 url中一定有 query 并且包含code
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        print("授权码：\(code)")
        
        WBNetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            }else{
                //SVProgressHUD.showInfo(withStatus: "登录成功")
                
                //发送登录成功通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue:WBUserLoginSuccessedNotofication), object: nil)
                
                self.close()
            }
        }
        //print("加载请求 ---\(request.url?.query)")
        //print("加载请求 ---\(request.url?.absoluteString)")
        //从https://baidu.com中获取code 如果有code则授权成功，如果没有授权失败
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
